package com.dinadi.yidi.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.LvProductDetailsAdpater;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.OrderDetailsBean;
import com.dinadi.yidi.bean.OrderDetailsEntity;
import com.dinadi.yidi.bean.OrderDetailsRequest;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.view.CommonDialogUtils;
import com.dinadi.yidi.ui.view.MyListView;
import com.dinadi.yidi.utils.FormatCurrentData;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.pingplusplus.android.Pingpp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2017/7/11   产品订单详情
 * Time: 16:52
 */
public class ProductOrderDetailsActivity extends BaseActivity {
    private View view;
    private TextView tvTitle, rightText;
    private RelativeLayout see_logistics_details;
    private TextView tv_logistics_status, tv_consignee, tv_consignee_phone, tv_consignee_place;
    private TextView tv_product_nums, tv_total, tv_product_freight, tv_amount_paid, pay_method, text_remarks, tv_order_id, tv_order_createTime, tv_logistics_status_time;
    private TextView tv_coupon, tv_coupon_price;
    private ImageView img_function, confirm_receipt;
    private MyListView lv_product_details;
    private List<OrderDetailsRequest> dataList = new ArrayList<>();
    private CommonDialogUtils  phoneDialog;
    private LvProductDetailsAdpater lv_adapter;
    /*联系电话*/
    private String phoneNumber = "15101570380";
    private String orderId, token,id,courierNum,state, stateNum, payType;



    @Override
    protected View getLayout() {
        view = LayoutInflater.from(ProductOrderDetailsActivity.this).inflate(R.layout.activity_product_order_details, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(R.string.text_order_details);
        rightText = (TextView) view.findViewById(R.id.text_title_right);
        rightText.setText(R.string.text_kefu);
        see_logistics_details = (RelativeLayout) view.findViewById(R.id.see_logistics_details);
        tv_logistics_status = (TextView) view.findViewById(R.id.tv_logistics_status);
        tv_consignee = (TextView) view.findViewById(R.id.tv_consignee);
        tv_consignee_phone = (TextView) view.findViewById(R.id.tv_consignee_phone);
        tv_consignee_place = (TextView) view.findViewById(R.id.tv_consignee_place);
        tv_product_nums = (TextView) view.findViewById(R.id.tv_product_nums);
        tv_total = (TextView) view.findViewById(R.id.tv_total);
        tv_product_freight = (TextView) view.findViewById(R.id.tv_product_freight);
        tv_amount_paid = (TextView) view.findViewById(R.id.tv_amount_paid);
        pay_method = (TextView) view.findViewById(R.id.pay_method);
        text_remarks = (TextView) view.findViewById(R.id.text_remarks);
        tv_order_id = (TextView) view.findViewById(R.id.tv_order_id);
        tv_order_createTime = (TextView) view.findViewById(R.id.tv_order_createTime);
        img_function = (ImageView) view.findViewById(R.id.img_function);
        confirm_receipt = (ImageView) view.findViewById(R.id.confirm_receipt);
        tv_logistics_status_time = (TextView) view.findViewById(R.id.tv_logistics_status_time);
        tv_coupon = (TextView) view.findViewById(R.id.tv_coupon);
        tv_coupon_price = (TextView) view.findViewById(R.id.tv_coupon_price);
        lv_product_details = (MyListView) view.findViewById(R.id.lv_product_details);
        lv_adapter = new LvProductDetailsAdpater(ProductOrderDetailsActivity.this, dataList);
        lv_product_details.setAdapter(lv_adapter);
    }

    @Override
    protected void initListener() {

        registerClickListener(see_logistics_details, confirm_receipt, img_function, rightText);
    }

    @Override
    public void onResume() {
        super.onResume();

        String isRefresh = SharePreferencesHelper.getInstance(this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            token = SharePreferencesHelper.getInstance(this).getString("token");
            getProductDetails();
            SharePreferencesHelper.getInstance(this).putString("isRefresh", "no");
        }

    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        orderId = intent.getStringExtra("orderId");
        token = SharePreferencesHelper.getInstance(ProductOrderDetailsActivity.this).getString("token");
        getProductDetails();

    }

    public void getProductDetails() {

        OrderDetailsBean bean = new OrderDetailsBean();
        bean.setOrderId(orderId);
        bean.setToken(token);
        CommonInterface orderDetailsInterface = new CommonInterface(ProductOrderDetailsActivity.this, httpListener);
        orderDetailsInterface.getInterface("16004", JSON.toJSONString(bean));

    }

    @Override
    protected void clickEvent(View v) {

        switch (v.getId()) {
            case R.id.see_logistics_details:
                /*查看物流详情*/
                if (courierNum != null && !"".equals(courierNum)) {
                    Intent intent = new Intent(ProductOrderDetailsActivity.this, LogisticsDetailsActivity.class);
                    intent.putExtra("courierNum", courierNum);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast("暂无物流信息");
                }

                break;
            case R.id.confirm_receipt:
                /*1*/
                state = tv_logistics_status.getText().toString();
                if (state.equals(getResources().getString(R.string.text_shipped))) {
                    //申请退款
//                    stateNum = "7";
//                    myDialog2 = new CommonDialogUtils(ProductOrderDetailsActivity.this);
//                    myDialog2.setContent(R.string.refund_is);
//                    myDialog2.setDialogCallback(dialogcallback2);
//                    myDialog2.show();
                    Intent intent = new Intent(ProductOrderDetailsActivity.this, RefundRequestActivity.class);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);

                } else if (state.equals(getResources().getString(R.string.text_un_paid))) {
                    //去付款
                      /*获取ping++支付Charge*/
                    pingCharge();
                }
                break;
            case R.id.img_function:
                /*2*/
                state = tv_logistics_status.getText().toString();
                if (state.equals(getResources().getString(R.string.text_paid))) {
                     /*申请退款*/
//                    stateNum = "7";
//                    myDialog2 = new CommonDialogUtils(ProductOrderDetailsActivity.this);
//                    myDialog2.setContent(R.string.refund_is);
//                    myDialog2.setDialogCallback(dialogcallback2);
//                    myDialog2.show();
                    Intent intent = new Intent(ProductOrderDetailsActivity.this, RefundRequestActivity.class);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);
                } else if (state.equals(getResources().getString(R.string.text_shipped))) {
                    // 确认收货
                    stateNum = "4";
                    CommonDialogUtils goodsReceiptDialog = new CommonDialogUtils(ProductOrderDetailsActivity.this);
                    goodsReceiptDialog.setContent(R.string.goods_receipt_is);
                    goodsReceiptDialog.setDialogCallback(dialogcallback2);
                    goodsReceiptDialog.show();
//                    confirmReceipt();
                } else if (state.equals(getResources().getString(R.string.text_successful_trade))) {
                    //删除
                    deleteOrder();
                } else if (state.equals(getResources().getString(R.string.text_tansaction_losed))) {
                    //删除
                    deleteOrder();
                } else if (state.equals(getResources().getString(R.string.text_refund))) {
                    //删除
                    deleteOrder();
                } else if (state.equals(getResources().getString(R.string.text_un_paid))) {
                    //取消订单
                    stateNum = "9";
                    CommonDialogUtils myDialog2 = new CommonDialogUtils(ProductOrderDetailsActivity.this);
                    myDialog2.setContent(R.string.older_is);
                    myDialog2.setDialogCallback(dialogcallback2);
                    myDialog2.show();

                }
                break;
            case R.id.text_title_right:
                phoneDialog = new CommonDialogUtils(ProductOrderDetailsActivity.this);
                phoneDialog.setContent("拨号：" + phoneNumber);
                phoneDialog.setDialogCallback(phone_Dialogcallback);
                phoneDialog.show();
                break;
            default:
                break;
        }
    }

    private void pingCharge() {
        OrderDetailsBean bean = new OrderDetailsBean();
        bean.setOrderIds(orderId);
        bean.setToken(token);
        bean.setClientIp("0.0.0.0");
        bean.setPayType(payType);
        CommonInterface commonInterface = new CommonInterface(ProductOrderDetailsActivity.this, pingHttpListener);
        commonInterface.getInterface("16014", JSON.toJSONString(bean));
    }

    /*4 确认收货   7申请退款   9 取消*/
    private void confirmReceipt() {
        OrderDetailsBean bean = new OrderDetailsBean();
        bean.setOrderId(orderId);
        bean.setToken(token);
        bean.setStatus(stateNum);
        CommonInterface orderDetailsInterface = new CommonInterface(ProductOrderDetailsActivity.this, confirmHttpListener);
        orderDetailsInterface.getInterface("16006", JSON.toJSONString(bean));
    }


    /*删除订单*/
    private void deleteOrder() {
        CommonDialogUtils myDialog = new CommonDialogUtils(ProductOrderDetailsActivity.this);
        myDialog.setContent(R.string.whether_is_delect);
        myDialog.setDialogCallback(dialogcallback);
        myDialog.show();

    }

    /**
     * 设置mydialog需要处理的事情
     */
    CommonDialogUtils.Dialogcallback dialogcallback = new CommonDialogUtils.Dialogcallback() {
        @Override
        public void dialogdo() {
            OrderDetailsBean bean = new OrderDetailsBean();
            bean.setOrderId(orderId);
            bean.setToken(token);
            CommonInterface orderDetailsInterface = new CommonInterface(ProductOrderDetailsActivity.this, deleteHttpListener);
            orderDetailsInterface.getInterface("16013", JSON.toJSONString(bean));
        }
    };

    CommonDialogUtils.Dialogcallback dialogcallback2 = new CommonDialogUtils.Dialogcallback() {
        @Override
        public void dialogdo() {
            confirmReceipt();
        }
    };

    CommonDialogUtils.Dialogcallback phone_Dialogcallback = new CommonDialogUtils.Dialogcallback() {
        @Override
        public void dialogdo() {
            //跳转登录页面
            //Android跳转到拨号界面，同时传递电话号码
            Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));//跳转到拨号界面，同时传递电话号码
            startActivity(dialIntent);
            phoneDialog.dismiss();
        }
    };
    /*确认购买*/

    HttpListener pingHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String charge = JsonUtil.getFieldValue(response, "charge");
                id = JsonUtil.getFieldValue(charge, "id");
                //参数一：Activity 表示当前调起支付的Activity
                //参数二：data 表示获取到的charge或order的JSON字符串
                Pingpp.createPayment(ProductOrderDetailsActivity.this, charge);

            } else if (errCode.equals("9974")) {
                ToastUtil.showToast("您的订单已超时，请重新下单哦~");
            } else {
                ToastUtil.showToast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
            /* 处理返回值
             * "success" - 支付成功
             * "fail"    - 支付失败
             * "cancel"  - 取消支付
             * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
             * "unknown" - app进程异常被杀死(一般是低内存状态下,app进程被杀死)
             */
                if (result.equals("success")) {
                    OrderDetailsBean bean = new OrderDetailsBean();
                    bean.setOrderIds(orderId);
                    bean.setPayType(payType);
                    bean.setChargeId(id);
                    bean.setToken(token);
                    CommonInterface commonInterface = new CommonInterface(ProductOrderDetailsActivity.this, orderStateHttpListener);
                    commonInterface.getInterface("16015", JSON.toJSONString(bean));
                } else if (result.equals("fail")) {
                    ToastUtil.showToast("支付失败");
                } else if (result.equals("cancel")) {
                    ToastUtil.showToast("取消支付");

                } else if (result.equals("invalid")) {
                    ToastUtil.showToast("支付插件未安装");
                } else if (result.equals("unknown")) {
                    ToastUtil.showToast("app进程异常被杀死");
                }
                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
            }
        }
    }

    HttpListener orderStateHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                ToastUtil.showToast("支付成功");
//                Intent intent = new Intent(ProductOrderDetailsActivity.this, PaymentResultsActivity.class);
//                intent.putExtra("orderId", orderId);
//                intent.putExtra("totalPrice", totalPrice);
//                startActivity(intent);
//                SharePreferencesHelper.getInstance(ProductOrderDetailsActivity.this).putString("isRefresh", "is");
//                ProductOrderDetailsActivity.this.finish();
                SharePreferencesHelper.getInstance(ProductOrderDetailsActivity.this).putString("isRefresh", "yes");
                ProductOrderDetailsActivity.this.finish();
            } else {
                ToastUtil.showToast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };
    HttpListener confirmHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                SharePreferencesHelper.getInstance(ProductOrderDetailsActivity.this).putString("isRefresh", "yes");
                ToastUtil.showToast("操作成功");
                ProductOrderDetailsActivity.this.finish();
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("操作失败");
        }
    };

    HttpListener deleteHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                ToastUtil.showToast("删除成功");
                SharePreferencesHelper.getInstance(ProductOrderDetailsActivity.this).putString("isRefresh", "yes");
                ProductOrderDetailsActivity.this.finish();
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("删除失败");

        }
    };
    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            dataList.clear();
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String createTime = JsonUtil.getFieldValue(response, "createTime");
                String status = JsonUtil.getFieldValue(response, "status");
                if (status.equals("1")) {
                    tv_logistics_status.setText(R.string.text_un_paid);
                    /*1去付款  2 取消订单*/


//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    Date staerTime = FormatCurrentData.StrToDate(createTime);
//                    long time = 30 * 60 * 1000;//30分钟
//                    Date afterDate = new Date(staerTime.getTime() + time);//30分钟后的时间
//                    tv_logistics_status_time.setText("(订单将于" + sdf.format(afterDate) + "自动取消，请尽快支付)");

                    Date startTime = FormatCurrentData.StrToDate(createTime);
                    long time = 30 * 60 * 1000;//30分钟
                    Date afterDate = new Date(startTime.getTime() + time);//30分钟后的时间
                    Date curDate = new Date(System.currentTimeMillis());//获取当前时间       
                    long surplus = afterDate.getTime() - curDate.getTime();
                    if (surplus > 0) {
                        tv_logistics_status_time.setVisibility(View.VISIBLE);
                        TimeCount timeCount = new TimeCount(surplus, 1000);// 构造CountDownTimer对象
                        timeCount.start();// 开始计时
                    } else {
                        tv_logistics_status_time.setVisibility(View.GONE);
                    }

                    confirm_receipt.setImageResource(R.drawable.icon_pay);
                    img_function.setImageResource(R.drawable.icon_cancellation_of_order);
                } else if (status.equals("2")) {
                    tv_logistics_status.setText(R.string.text_paid);
                    /*2申请退款*/
                    confirm_receipt.setVisibility(View.GONE);
                    img_function.setImageResource(R.drawable.order_icon_refund);
                } else if (status.equals("3")) {
                    tv_logistics_status.setText(R.string.text_shipped);
                    /*1申请退款 2确认收货*/
                    confirm_receipt.setImageResource(R.drawable.order_icon_refund);
                    img_function.setImageResource(R.drawable.icon_follow_selected_goods_receipt);
                } else if (status.equals("4")) {
                    tv_logistics_status.setText(R.string.text_successful_trade);
                    /*2删除*/
                    confirm_receipt.setVisibility(View.GONE);
                    img_function.setImageResource(R.drawable.order_icon_delate);

                } else if (status.equals("7")) {
                    tv_logistics_status.setText(R.string.text_pply_or_refund);
                    confirm_receipt.setVisibility(View.GONE);
                    img_function.setImageResource(R.drawable.icon_refund);
                } else if (status.equals("8")) {
                     /*2删除*/
                    tv_logistics_status.setText(R.string.text_refund);
                    confirm_receipt.setVisibility(View.GONE);
                    img_function.setImageResource(R.drawable.order_icon_delate);
                } else if (status.equals("9")) {
                     /*2删除*/
                    tv_logistics_status.setText(R.string.text_tansaction_losed);
                    confirm_receipt.setVisibility(View.GONE);
                    img_function.setImageResource(R.drawable.order_icon_delate);
                }
                String recipients = JsonUtil.getFieldValue(response, "recipients");
                tv_consignee.setText(recipients);
                String phone = JsonUtil.getFieldValue(response, "phone");
                tv_consignee_phone.setText(phone);
                String address = JsonUtil.getFieldValue(response, "address");
                tv_consignee_place.setText(address);

                /*物流单号*/
                courierNum = JsonUtil.getFieldValue(response, "courierNum");

                OrderDetailsEntity beanRequest = JsonUtil.parseJsonToBean(response.toString(), OrderDetailsEntity.class);
                dataList.addAll(beanRequest.getOrderDetails());

                lv_adapter.notifyDataSetChanged();
                String productNum = JsonUtil.getFieldValue(response, "productNum");
                tv_product_nums.setText("共" + productNum + "件产品");
                /*商品总价*/
                String totalPrice = JsonUtil.getFieldValue(response, "totalPrice");

                String postage = JsonUtil.getFieldValue(response, "postage");
                if (postage != null && !"".equals(postage)) {
                    tv_product_freight.setText("￥" + postage);
                } else {
                    tv_product_freight.setText("￥0");
                }

                String payPrice = JsonUtil.getFieldValue(response, "payPrice");
                tv_total.setText("￥" + totalPrice);
                tv_amount_paid.setText("￥" + payPrice);
//                "payType": "付款方式 [int] 1-微信 2-支付宝",
                payType = JsonUtil.getFieldValue(response, "payType");
                if (payType.equals("1")) {
                    pay_method.setText("微信");
                } else {
                    pay_method.setText("支付宝");
                }
                String remark = JsonUtil.getFieldValue(response, "remark");
                if (remark.equals("")) {
                    text_remarks.setText("无");
                } else {
                    text_remarks.setText(remark);
                }
                orderId = JsonUtil.getFieldValue(response, "orderId");

                tv_order_id.setText(orderId);
                tv_order_createTime.setText(createTime);
                /*"是否使用优惠卷 1-使用 2-未使用"*/
                String isUseCoupon = JsonUtil.getFieldValue(response, "isUseCoupon");
                /*优惠价格*/
                String couponPrice = JsonUtil.getFieldValue(response, "couponPrice");
                if (isUseCoupon.equals("1")) {
                    tv_coupon_price.setText("-￥" + couponPrice);
                    tv_coupon.setVisibility(View.VISIBLE);
                    tv_coupon_price.setVisibility(View.VISIBLE);
                } else {
                    tv_coupon.setVisibility(View.GONE);
                    tv_coupon_price.setVisibility(View.GONE);
                }


            } else {
                ToastUtil.showToast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            getProductDetails();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            long time = millisUntilFinished / 1000;
            if (time <= 59) {
                tv_logistics_status_time.setText(String.format("支付剩余时间：  00:%02d", time));
            } else {
                tv_logistics_status_time.setText(String.format("支付剩余时间：  %02d:%02d", time / 60, time % 60));
            }
        }
    }


}
